package com.axin.web.controller;

import com.axin.blog.api.domain.WebUser;
import com.axin.common.core.constant.SecurityConstants;
import com.axin.common.core.domain.model.LoginBody;
import com.axin.common.core.domain.web.AjaxResult;
import com.axin.web.annotation.CurrentUser;
import com.axin.web.annotation.IgnoreAuth;
import com.axin.web.service.WebLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author axin
 * @Date 2021/11/7 10:52
 **/
@RestController
@RequestMapping("/auth")
public class ApiAuthController {

    @Autowired
    private WebLoginService loginService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @IgnoreAuth
    @PostMapping("/login")
    public AjaxResult login(@Validated @RequestBody LoginBody loginBody) {

        // 生成令牌
        String token = loginService.login(loginBody);

        Map<String, Object> ajax = new HashMap<>(1);
        ajax.put(SecurityConstants.TOKEN, token);
        return AjaxResult.success(ajax);
    }

    @IgnoreAuth
    @PostMapping("/register")
    public AjaxResult register(@Validated @RequestBody WebUser user) {

        // 生成令牌
        return loginService.register(user);
    }

    @GetMapping("/getInfo")
    public AjaxResult getInfo(@CurrentUser WebUser user) {
        return AjaxResult.success(user);
    }


    @RequestMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        loginService.logout(request);
        return AjaxResult.success();
    }

}
